package com.yasaka.stock.service;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import com.yasaka.stock.common.FileUtils;
import com.yasaka.stock.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

@Service
@Slf4j
public class FileService {

    @Value("${qiniu.downloadHost}")
    private String downloadHost;
    @Value("${qiniu.uploadHost}")
    private String uploadHost;
    @Value("${qiniu.bucketName}")
    private String bucketName;
    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${file.savePath}")
    private String savePath;

    public String uploadRemoteFileToQiNiu(String fileUrl) throws MyException {
        HttpURLConnection conn = null;
        try {
            String realName = "";
            URL url = new URL(fileUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            //获取文件名和扩展名
            //先连接一次，解决跳转下载
            int responseCode = conn.getResponseCode();
            if(responseCode!=200){
                throw new MyException("file is not exist");
            }
            //获取header 确定文件名和扩展名
            realName = conn.getHeaderField("Content-Disposition");
            if(StringUtils.isBlank(realName) || realName.indexOf("filename")<0){
                throw new MyException("file is not exist");
            }else{
                realName = URLDecoder.decode(realName.substring(realName.indexOf("filename")+10,realName.length()-1),"UTF-8");
                realName = realName.substring(0,realName.indexOf("\""));
            }
            realName = FileUtils.diskNameProductor(realName);
            Configuration cfg = new Configuration(Zone.autoZone());
            // bucket资源管理工具类
            Auth auth = Auth.create(accessKey, secretKey);
            BucketManager bucketManager = new BucketManager(auth, cfg);
            FetchRet fetchRet;
            try {
                fetchRet = bucketManager.fetch(fileUrl, bucketName, realName);
                if(fetchRet!=null){
                    fileUrl = downloadHost.trim() + realName;
                }else{
                    throw new MyException("upload fail");
                }
            } catch (QiniuException e) {
                log.error(e.getMessage(), e);
                throw new MyException(e.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            throw new MyException(e.getMessage());
        } finally {
            conn.disconnect();
        }
        return fileUrl;
    }

    public String uploadLocalFileToQiNiu(MultipartFile file) throws MyException {
        String localFile = null;
        if (file.isEmpty()) {
            throw new MyException("file is not exists");
        }
        String fileUrl = "";
        try {
            String realName = FileUtils.diskNameProductor(file.getOriginalFilename());
            Configuration cfg = new Configuration(Zone.zone0());
            UploadManager uploadManager = new UploadManager(cfg);
            Response response;
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucketName);
            localFile = savePath + File.separator + realName;
            FileUtils.saveFileFromInputStream(file.getInputStream(),localFile);
            response = uploadManager.put(localFile, realName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
            if(StringUtils.isNotEmpty(putRet.key)){
                fileUrl = downloadHost.trim() + realName;
                new File(localFile).delete();
            }else{
                new File(localFile).delete();
                throw new MyException("file is upload fail"+ response.bodyString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            throw new MyException(e.getMessage());
        }
        return fileUrl;
    }

}
